<template>
    <div class="users-section">
        <div class="section-header">
            <h2>用户管理</h2>
            <el-button type="primary" v-if="userType === 'admin'" @click="showCreateUserDialog = true">
                ➕ 添加用户
            </el-button>
        </div>

        <div class="table-container">
            <el-table :data="users" style="width: 100%">
                <el-table-column prop="username" label="用户名" width="150" />
                <el-table-column prop="phone" label="手机号" width="150" />
                <el-table-column prop="email" label="邮箱" width="200" />
                <el-table-column prop="companyName" label="企业名称" width="200" />
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                            {{ row.status === 1 ? '正常' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="250">
                    <template #default="{ row }">
                        <el-button size="small" @click="viewUser(row)">查看</el-button>
                        <el-button size="small" @click="editUser(row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteUser(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 查看详情对话框 -->
        <el-dialog v-model="showDetailDialog" :title="detailTitle" width="800px">
            <div v-if="currentItem" class="detail-content">
                <div class="user-detail">
                    <h3>{{ currentItem.username }}</h3>
                    <div class="detail-info">
                        <p><strong>手机号：</strong>{{ currentItem.phone }}</p>
                        <p><strong>邮箱：</strong>{{ currentItem.email }}</p>
                        <p><strong>企业名称：</strong>{{ currentItem.companyName }}</p>
                        <p><strong>状态：</strong>
                            <el-tag :type="currentItem.status === 1 ? 'success' : 'danger'">
                                {{ currentItem.status === 1 ? '正常' : '禁用' }}
                            </el-tag>
                        </p>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- 创建/编辑用户对话框 -->
        <el-dialog v-model="showCreateUserDialog" :title="editingUser ? '编辑用户' : '添加用户'" width="600px"
            @closed="resetUserForm">
            <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="userForm.username" placeholder="请输入用户名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="userForm.phone" placeholder="请输入手机号" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="userForm.email" placeholder="请输入邮箱" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="企业名称" prop="companyName">
                            <el-input v-model="userForm.companyName" placeholder="请输入企业名称" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="密码" prop="password" v-if="!editingUser">
                    <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
                </el-form-item>

                <el-form-item label="用户状态">
                    <el-radio-group v-model="userForm.status">
                        <el-radio label="active">正常</el-radio>
                        <el-radio label="inactive">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showCreateUserDialog = false">取消</el-button>
                    <el-button type="primary" @click="saveUser" :loading="createLoading">
                        {{ editingUser ? '更新' : '添加' }}
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import userApi from '@/api/user'

const userType = ref(localStorage.getItem('userType') || 'enterprise');
const showCreateUserDialog = ref(false);
const editingUser = ref(null);
const userFormRef = ref();
const createLoading = ref(false);
const showDetailDialog = ref(false);
const detailTitle = ref('');
const currentItem = ref(null);
const users = ref([]);
const loading = ref(true);

const userForm = ref({
    id: null,
    username: '',
    phone: '',
    email: '',
    companyName: '',
    password: '',
    status: 'active'
});

const userRules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    companyName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
    password: [{ required: false, message: '请输入密码', trigger: 'blur' }]
};

const fetchUsers = async () => {
    loading.value = true;
    try {
        const res = await userApi.getUserList();
        // 根据DynamicsManagement.vue的实现，我们假设分页数据在res.content
        // 如果后端直接返回数组，这里应为 res
        users.value = res.content || res; 
    } catch (error) {
        ElMessage.error('获取用户列表失败');
        console.error(error);
    } finally {
        loading.value = false;
    }
};

onMounted(fetchUsers);

const viewUser = (user) => {
    currentItem.value = user;
    detailTitle.value = '用户详情';
    showDetailDialog.value = true;
};

const editUser = (user) => {
    editingUser.value = user;
    userForm.value = { ...user, password: '', status: user.status === 1 ? 'active' : 'inactive' };
    showCreateUserDialog.value = true;
};

const deleteUser = async (user) => {
    try {
        await ElMessageBox.confirm(`确定要删除用户 "${user.username}" 吗？`, '确认删除', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        await userApi.deleteUser(user.id);
        ElMessage.success('用户删除成功');
        await fetchUsers();

    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除用户失败');
        }
    }
};

const resetUserForm = () => {
    userForm.value = {
        id: null,
        username: '',
        phone: '',
        email: '',
        companyName: '',
        password: '',
        status: 'active'
    };
    editingUser.value = null;
    if (userFormRef.value) {
        userFormRef.value.resetFields();
    }
};

const saveUser = async () => {
    if (!userFormRef.value) return;
    try {
        const valid = await userFormRef.value.validate();
        if (!valid) return;

        createLoading.value = true;

        const userData = { ...userForm.value };
        userData.status = userForm.value.status === 'active' ? 1 : 0;
        
        // 从userData中移除id，因为创建用户时不需要
        const { id, ...createData } = userData;

        if (editingUser.value) {
            if (!userData.password) {
                delete userData.password;
            }
            await userApi.updateUser(editingUser.value.id, userData);
            ElMessage.success('用户更新成功！');
        } else {
            if (!createData.password) {
                ElMessage.error('请输入密码');
                createLoading.value = false;
                return;
            }
            await userApi.createUser(createData);
            ElMessage.success('用户创建成功！');
        }

        showCreateUserDialog.value = false;
        await fetchUsers();

    } catch (error) {
        ElMessage.error('操作失败，请重试');
    } finally {
        createLoading.value = false;
    }
};
</script>

<style scoped>
.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.section-header h2 {
    margin: 0;
    color: #333;
}

.table-container {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.detail-content {
    line-height: 1.6;
}

.detail-content h3 {
    margin-bottom: 20px;
    color: #333;
    border-bottom: 2px solid #f0f0f0;
    padding-bottom: 10px;
}

.detail-info {
    margin-bottom: 20px;
}

.detail-info p {
    margin: 10px 0;
    color: #666;
}
</style>